package com.ctg.behavior.calc.impala.transfer;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.common.calc.CtCalc;
import com.ctg.behavior.common.calc.CtCalcTotal;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtTotalTransfer implements CtSQLTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtCalcTotal)) {
			log.warn("calcObject is not CtCalcTotal, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			log.warn("calcObject sqlParam: {}", JSON.toJSON(sqlParam));
			return "";
		}
		CtCalcTotal calcTotal = (CtCalcTotal) calcObject;
		log.info("calcTotal={}", JSON.toJSONString(calcTotal));

		StringBuilder impalaSQL = new StringBuilder();

		impalaSQL.append(" SELECT COUNT(*) AS total FROM ( ");
		// 执行列表SQL生成器
		String detailSQL = calcTotal.getDetailSQL();
		// 移除最后的ORDER BY, 及LIMIT, 不能移除GROUP BY
		int index = detailSQL.indexOf("ORDER");
		if (index < 0) {
			index = detailSQL.indexOf("LIMIT");
		}
		if (index > 0) {
			detailSQL = detailSQL.substring(0, index);
		}
		impalaSQL.append(detailSQL);
		impalaSQL.append(" ) TP0 ");

		String retSQL = impalaSQL.toString();
		log.info("CalcSQL={}", retSQL);
		
		return retSQL;
	}

}
